package com.mc.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.mc.api.domain.User;
import com.mc.api.service.UserService;
import com.mc.api.tools.AESUtils;
import com.mc.api.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

@Api(value = "测试接口", tags = "用户管理相关的接口", description = "用户测试接口")
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);



    @PostMapping("/login")
    @ResponseBody
    @ApiOperation("登录认证接口")
    public Object login(@RequestBody User user) throws JsonProcessingException, UnsupportedEncodingException {
        //可以在此处检验用户密码
        User userDB = userService.selectUserByTel(user.getUserName());
        if(userDB == null){
            userDB = userService.selectUserByUserName(user.getUserName());
        }
//        AESUtils aes = new AESUtils();
//        byte[] decode = aes.parseHexStr2Byte(user.getPassword());
//        byte[] decryptResult = aes.decrypt(decode);
        log.info("当前登录用户:"+user.getUserName());

        // 解密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        JSONObject result = new JSONObject();
        if(userDB.getStatus().equals("0")){
            if(passwordEncoder.matches(user.getPassword(), userDB.getPassword())){

                String token= TokenUtil.sign(user);
                List<Integer> list = userService.selectUserRole(userDB.getUserId());
                HashMap<String,Object> hs=new HashMap<>();
                hs.put("token",token);
                hs.put("deptId",userDB.getDeptId());
                hs.put("nickName",userDB.getNickName());
                hs.put("role",list);
                hs.put("userId",userDB.getUserName());
                result.put("code", "200");
                result.put("msg", "登录成功");
                result.put("data",hs);
                userService.updateUserLast(userDB.getUserName());
                log.info("登录成功");
            }else{
                result.put("code", "501");
                result.put("msg", "密码错误");
            }

        }else{
            result.put("code", "503");
            result.put("msg", "账号禁用");
        }


        return result;

    }
}
